<template>
  <basic-container >
    <avue-form
      v-if="this.selectMer.userMerchantType !== 3 &&this.selectMer.userMerchantType !== 4"
      ref="excelForm"
      v-model="excelForm"
      :defaults.sync="defaults"
      :option="excelOption"
    >

      <template slot-scope="{}" slot="rpiNo">
        <select-page
          ref="searchRpiSelect"
          label="rpiName"
          value="rpiNo"
          :select.sync="excelForm.rpiNo"
          :url="website.searchLink.merchantUrl"
          placeholder-text="所属商户"
          filter-key="searchParam"
          :params="{rpiGroup:selectMer.rpiNo}"
          @update:select="searchrpiNoChange"  @clear:select="searchrpiNoClear"
        ></select-page>
      </template>
      <template slot-scope="{}" slot="rpsNo">
        <select-page
          ref="searchrpsSelect"
          label="rpsName"
          value="rpsNo"
          :select.sync="excelForm.rpsNo"
          :url="website.searchLink.rpsUrl"
          placeholder-text="门店"
          filter-key="searchParam"
          :params="rpsNoParams"
          @update:select="searchrpsNoChange" @clear:select="searchrpsNoClear"
        ></select-page>
      </template>
      <template slot-scope="{}" slot="rpstNo">
        <select-page
          ref="searchrpstSelect"
          label="rpstName"
          value="rpstNo"
          :select.sync="excelForm.rpstNo"
          :url="website.searchLink.rpstUrl"
          placeholder-text="操作员"
          filter-key="searchParam"
          :params="rpstNoParams"
        ></select-page>
      </template>
      <template slot="menuForm">
        <div class="alertWrap">
          <div>1.开始日期与结束日期最大间隔 31 天</div>
          <div>2.开始日期与结束日期不能跨年</div>
        </div>
        <div class="btnWrap">
          <el-button  icon="el-icon-download" type="primary" style="margin-left:350px;" @click="handleSubmit" v-if="permissionList.exportBtn">立即下载</el-button>
        </div>
      </template>
    </avue-form>
    <!-- 检测是否选择商户 -->
    <selectMer :dialogVisible="tipsShow" />
    <!-- 收银员|门店 无权限 -->
    <div class="qxWrap" v-if="this.selectMer.userMerchantType === 3||this.selectMer.userMerchantType === 4">
      <div class="qxH1">暂无权限</div>
    </div>
  </basic-container>
</template>

<script>
import { getExport } from "@/api/rb-merchant/dealManagement/dealManagement";
// import { getList as getStoreList } from "@/api/rb-merchant/posStore/pos_store";
// import { getList as getStaffList } from "@/api/rb-merchant//posStaff/pos_staff";
import { mapGetters } from "vuex";
import { dateFormat } from "@/util/date";
// import { getMerchantList } from "@/api/rb-merchant/posinfo/pos_info";
import { getDictionary } from "@/api/system/dict";
import selectPage from "@/components/select-page/select-page";

export default {
  components: {
    selectPage
  },
  data() {
    var validateTimeData = (rule, value, callback)=>{
      if(value.length){
        if( new Date(value[0]).getFullYear() === new Date(value[1]).getFullYear()){
          if(((new Date(value[1]).getTime() - new Date(value[0]).getTime()) / (3600 * 1000 * 24)) > 31){
            this.excelForm.timeData=[];
            this.excelForm.beginTime = "";
            this.excelForm.endTime = "";
            callback(new Error('开始日期与结束日期最大间隔 31 天!'));
          }else {
            callback();
          }
        }else{
          callback(new Error('开始日期与结束日期不能跨年'));
        }
      }else{
        callback(new Error('请选择对账时间段，开始日期与结束日期最大间隔 31 天!'));
      }
    };
    return {
      rpsNoParams:{},
      rpstNoParams:{},
      tipsShow:false,
      defaults:{},
      excelForm: {},
      excelOption: {},
      option: {
        submitBtn: false,
        emptyBtn: false,
        labelWidth: 160, //弹出表单的标题的统一宽度
        menuPosition: 'left',
        span:11,
        labelWidth:120,
        column: [
          {
            label: '商户',
            prop: 'rpiNo',
            type: 'select',
            props: {
              label: 'rpiName',
              value: 'rpiNo',
              desc: 'rpiNo'
            },
            row:true,
            display:false,
          },
          {
            label: '门店',
            prop: 'rpsNo',
            type: 'select',
            props: {
              label: 'rpsName',
              value: 'rpsNo',
              desc: 'rpsNo'
            },
            rules: [
              {
                // required: true,
                message: '请选择门店',
                trigger: 'blur'
              }
            ],
            // span: 13,
            row:true,
          },
          {
            label: '收银员',
            prop: 'rpstNo',
            type: 'select',
            // dataType: "number",
            props: {
              label: 'rpstName',
              value: 'rpstNo',
              desc: 'rpstNo'
            },
            rules: [
              {
                // required: true,
                message: '请选择收银员',
                trigger: 'blur'
              }
            ],
            // span: 13,
            row:true,
          },
          {
            label: '支付状态',
            prop: 'rptPayStates',
            type: 'checkbox',
            props: {
              label: "dictValue",
              value: "dictKey"
            },
            all:true,
            dicUrl: `/api/blade-system/dict/dictionary?code=bill_statue`,
            dicFormatter:(data)=>{
              // data.data.unshift({dictValue: "全部",dictKey: ""});
              return data.data
            },
            span: 24,
            row:true,
          },
          {
            label: "支付方式",
            prop: "rptPayTypes",
            type: 'checkbox',
            props: {
              label: "dictValue",
              value: "dictKey",
            },
            all:true,
            // dataType: "number",
            dicUrl: "/api/blade-system/dict/dictionary?code=rpt_pay_type",
            dicFormatter:(data)=>{
              // data.data.unshift({dictValue: "全部",dictKey: ""});
              return data.data
            },
            span: 24,
            row:true,
          },
          {
            label: "对账单时间段",
            prop: "timeData",
            type: "daterange",
            searchRange: true,
            defaultTime:['00:00:00', '23:59:59'],
            format:'yyyy-MM-dd HH:mm:ss',
            valueFormat:'yyyy-MM-dd HH:mm:ss',
            startPlaceholder: "对账单开始时间",
            endPlaceholder: "对账单结束时间",
            search: true,
            rules: [
              {
                required: true,
                validator: validateTimeData,
                trigger: "change",
              },
            ],
            //span: 10,
            row:true,
            pickerOptions: {
              disabledDate(time) {
                let currentTime = new Date(dateFormat(new Date(),'yyyy-MM-dd')).getTime();
                let t = new Date(dateFormat(time,'yyyy-MM-dd')).getTime();
                let pastTime = new Date(dateFormat(new Date(Date.now() - 3600 * 1000 * 24 * 90),'yyyy-MM-dd')).getTime();

                if(currentTime < t){
                  return true
                }else if(pastTime >= t){
                  return true
                }else{
                  return false
                }
              }
            }
          }
        ],
      },
      rpsNoList:[],//门店
      // staffList:[],//收银员
      rpiNoList:[],//商户
      rpiGroup:"",//集团商户编号

    };
  },
  computed: {
    ...mapGetters(["permission","selectMer"]),
    permissionList() {
      return {
        exportBtn: this.vaildData(this.permission.bill_export, false)
      };
    }
  },
  watch: {
    "excelForm.timeData"(val){
      if(val.length){
        this.excelForm.beginTime = val[0];
        this.excelForm.endTime = val[1];
      }else{
        this.excelForm.beginTime = "";
        this.excelForm.endTime = "";
      }
    }
  },
  created(){
    /* 检测是否选择了商户，没有选择跳转页面进行选择 */
    this.isSelect();
    // this.doGetDicts();
  },
  methods: {
    /**@desc门店改变 */
    searchrpsNoChange(value){
      if (value) {
        this.excelForm.rpstNo = "";

        let params = {
          rpsNo: value
        };
        
        if(this.selectMer.userMerchantType === 1){
          params.rpiGroup = this.rpiGroup
          if(this.excelForm.rpiNo){
            params.rpiNo = this.excelForm.rpiNo
          }
        }else{
          params.rpiNo = this.selectMer.rpiNo
        }
        

        this.$refs['searchrpstSelect'].getOptionList(params);
        this.$forceUpdate();
      }
    },
    /**@desc门店清空 */
    searchrpsNoClear(){
      this.excelForm.rpstNo = "";

      this.$refs['searchrpstSelect'].getOptionList();
      this.$forceUpdate();
    },
    /**@desc商户改变 */
    searchrpiNoChange(value){
      if (value) {
        this.excelForm.rpsNo = "";
        this.excelForm.rpstNo = "";

        let params = {
          rpiNo: value
        };
        this.$refs['searchrpsSelect'].getOptionList(params);
        this.$refs['searchrpstSelect'].getOptionList(params);
        this.$forceUpdate();
      }
    },
    /**@desc商户清空 */
    searchrpiNoClear(){
      this.excelForm.rpsNo = "";
      this.excelForm.rpstNo = "";

      let params = {
        rpiGroup: this.rpiGroup
      };

      this.$refs['searchrpsSelect'].getOptionList(params);
      this.$refs['searchrpstSelect'].getOptionList(params);
      this.$forceUpdate();
    },
    /* 字典 */
    doGetDicts() {
      getDictionary({ code: "bill_statue" }).then((res) => {
        this.rptPayStateList = res.data.data;
      });
      getDictionary({ code: "rpt_pay_type" }).then((res) => {
        this.rptPayTypeList = res.data.data;
      });
    },

    isSelect(){
      if(!this.selectMer.rpiNo){
        this.tipsShow=true;
      }else if(this.selectMer.userMerchantType === 1){
        // 集团商户
        this.rpiGroup = this.selectMer.rpiNo;
        this.rpsNoParams = {
          rpiGroup:this.selectMer.rpiNo
        }
        this.rpstNoParams = {
          rpiGroup:this.selectMer.rpiNo
        }

        let column = this.findObject(this.option.column, "rpiNo");
        column.display = true;

        this.excelOption=this.option;
      }else if(this.selectMer.userMerchantType === 2){
        // 商户
        this.rpiGroup = "";
        this.excelOption=this.option;

        this.rpsNoParams = {
          rpiNo:this.selectMer.rpiNo
        }
        this.rpstNoParams = {
          rpiNo:this.selectMer.rpiNo
        }
      }
    },

    // 获取商户
    // apiMerchantList(){
    //   getMerchantList(-1,-1,0).then((res) => {
    //     const data = res.data.data.records;
    //     const column = this.findObject(this.excelOption.column, "rpiNo");
    //     column.dicData = data;
    //   });
    // },

    // 获取门店
    // ApiListExportStore(param){
    //   getStoreList(-1,-1,param).then((res) => {
    //     this.rpsNoList = res.data.data.records;
    //     const column = this.findObject(this.excelOption.column, "rpsNo");
    //     column.dicData = this.rpsNoList;
    //   })
    // },

    // 下载
    handleSubmit(){
      let _this = this;
      _this.$refs.excelForm.validate((vaild,done)=>{
        if(vaild){
          _this.$confirm("是否下载对账单数据?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }).then(() => {
          let {rpiNo,rpsNo,rpstNo,rptPayStates,rptPayTypes,beginTime,endTime} = _this.excelForm;

          let param = {
            rpsNo,
            rpstNo,
            beginTime,
            endTime
          }
          if(this.selectMer.userMerchantType === 1){
            param.rpiNo = rpiNo; //集团商户
            param.rpiGroup = this.selectMer.rpiNo;
          }else if(this.selectMer.userMerchantType === 2){
            param.rpiNo = this.selectMer.rpiNo
          }

          if(rptPayStates.length){
            param.rptPayStateString= _this.excelForm.rptPayStates.join(",")
          }
          if(rptPayTypes.length){
            param.rptPayTypeString= _this.excelForm.rptPayTypes.join(",")
          }
          // 是否集团商户（1是集团商户0不是）

          getExport(param).then((res) => {
              //downloadFileExcel(res);
              this.$message({
                type: "success",
                message: res.data.msg
              });
              done()
            },
            (error) => {
              window.console.log(error);
              done()
            }
          );
        }).catch(() => {
          done()
        })
        }
      })
    }
  }
};
</script>


<style lang="scss" scoped>
.avue-form{
  padding-left: 200px;
}

/deep/ .avue-checkbox{
  display: flex !important;
}
.btnWrap{
  width: 25%;
  display: flex ;
  justify-content: flex-end;
}
.alertWrap{
  width: 100%;
  display: flex;
  justify-content: flex-end;
}
/deep/ .el-alert{
  width: 420px !important;
  padding:0 10px;
}

.alertWrap{
  padding-left: 120px;
  color: #E6A23C;
  display: flex ;
  flex-direction: column;
  align-items: flex-start;
}
</style>

